In [2]:
# ================================================================
# LAB 10. REGRESSION MODEL SELECTION (continued)
#
# STAT 415/615 - Regression
#
# Topics:
#   4. Sequential F-tests
#   5. Visualization: Scatterplot matrices
#
# ================================================================


# ================================================================
# PART 0. PREPARATION
# ================================================================

# Import the required Python libraries.

import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt

from pandas.plotting import scatter_matrix


# Load Longley's macroeconomic dataset.
#
# This dataset is included in the statsmodels library.
# It contains annual US economic data from 1947 through 1962.
#
# We will use the economic variables to predict the number
# of unemployed people (measured in hundreds of thousands
# in the original R dataset).

longley = sm.datasets.longley.load_pandas().data.copy()


# Rename variables to match their names in the R dataset.

longley = longley.rename(columns={
    "GNPDEFL": "GNP.deflator",
    "UNEMP": "Unemployed",
    "ARMED": "Armed.Forces",
    "POP": "Population",
    "TOTEMP": "Employed",
    "YEAR": "Year"
})


# Convert units to match the original R dataset.
#
# This is not necessary for variable selection, but it
# makes the regression coefficients comparable to R.

longley["GNP"] /= 1000
longley["Unemployed"] /= 10
longley["Armed.Forces"] /= 10
longley["Population"] /= 1000
longley["Employed"] /= 1000


# Arrange columns in the same order as in R.

longley = longley[
    ["GNP.deflator", "GNP", "Unemployed",
     "Armed.Forces", "Population", "Year", "Employed"]
]


# Examine the dataset.

print(longley.head())

print("\nVariable names:")
print(longley.columns.tolist())

print("\nNumber of observations:", len(longley))
   GNP.deflator      GNP  Unemployed  Armed.Forces  Population    Year  \
0          83.0  234.289       235.6         159.0     107.608  1947.0   
1          88.5  259.426       232.5         145.6     108.632  1948.0   
2          88.2  258.054       368.2         161.6     109.773  1949.0   
3          89.5  284.599       335.1         165.0     110.929  1950.0   
4          96.2  328.975       209.9         309.9     112.075  1951.0   

   Employed  
0    60.323  
1    61.122  
2    60.171  
3    61.187  
4    63.221  

Variable names:
['GNP.deflator', 'GNP', 'Unemployed', 'Armed.Forces', 'Population', 'Year', 'Employed']

Number of observations: 16
In [3]:
# ================================================================
# PART 4. SEQUENTIAL F-TESTS
# ================================================================

# Sequential selection procedures add or remove predictors
# one at a time, using partial F-tests.
#
# Unlike the AIC-based selection in Lab 9, the decision
# to add or remove a predictor depends on its p-value.
#
# We specify a significance level alpha.
#
# FORWARD SELECTION:
#   Start with the intercept-only model.
#   At each step, test all excluded predictors.
#   Add the predictor with the smallest partial F-test p-value,
#   provided that p-value is below alpha.
#   Stop when no excluded predictor meets the criterion.
#
# BACKWARD ELIMINATION:
#   Start with the full model.
#   At each step, test all included predictors.
#   Remove the predictor with the largest partial F-test
#   p-value, provided that p-value exceeds alpha.
#   Stop when all remaining predictors meet the criterion.
#
# The procedures use partial F-tests, comparing nested
# regression models.
#
# For a single predictor, the partial F-test is equivalent
# to the usual t-test for its regression coefficient.


# ------------------------------------------------
# 4A. Define the response and candidate predictors
# ------------------------------------------------

Y = longley["Unemployed"]

predictors = [
    "GNP.deflator",
    "GNP",
    "Armed.Forces",
    "Population",
    "Year",
    "Employed"
]


# Define a function to fit a regression model using
# any subset of these predictors.

def fit_model(selected):

    X = sm.add_constant(
        longley[selected],
        has_constant="add"
    )

    return sm.OLS(Y, X).fit()


# ------------------------------------------------
# 4B. Define the sequential F-test procedure
# ------------------------------------------------

# The following function performs forward selection
# or backward elimination.
#
# direction:
#   "forward"  - add significant predictors
#   "backward" - remove insignificant predictors
#
# alpha:
#   Significance level for the partial F-tests.
#
# correction:
#   If True, apply a stepwise Bonferroni adjustment
#   by dividing alpha by the number of candidate tests
#   performed at the current step.
#
# trace:
#   If True, display every selection step.
#
# The function returns the final fitted regression model.


def select_F(direction="forward", alpha=0.05,
             correction=False, trace=False):

    if direction not in ("forward", "backward"):
        raise ValueError("direction must be 'forward' or 'backward'")

    # Forward selection starts with no predictors.
    # Backward elimination starts with all predictors.

    selected = (
        [] if direction == "forward"
        else predictors.copy()
    )

    step = 0

    while True:

        current = fit_model(selected)

        # ----------------------------------------
        # Forward selection
        # ----------------------------------------

        if direction == "forward":

            remaining = [
                v for v in predictors if v not in selected
            ]

            if not remaining:
                break

            # Compare each enlarged model with the
            # current model using a partial F-test.

            tests = []

            for v in remaining:

                enlarged = fit_model(selected + [v])

                F, p, df = enlarged.compare_f_test(current)

                tests.append((v, F, p))

            # Select the predictor with the smallest p-value.

            variable, F, p = min(
                tests,
                key=lambda x: x[2]
            )

            # Bonferroni adjustment, if requested.

            cutoff = (
                alpha / len(tests)
                if correction else alpha
            )

            if p >= cutoff:
                break

            selected.append(variable)

            action = "Added"


        # ----------------------------------------
        # Backward elimination
        # ----------------------------------------

        else:

            if not selected:
                break

            # Compare the current model with each model
            # obtained by removing one predictor.

            tests = []

            for v in selected:

                reduced = fit_model(
                    [x for x in selected if x != v]
                )

                F, p, df = current.compare_f_test(reduced)

                tests.append((v, F, p))

            # Select the predictor with the largest p-value.

            variable, F, p = max(
                tests,
                key=lambda x: x[2]
            )

            cutoff = (
                alpha / len(tests)
                if correction else alpha
            )

            if p <= cutoff:
                break

            selected.remove(variable)

            action = "Removed"


        # Display the current selection step.

        step += 1

        if trace:

            print(
                f"Step {step}: {action} {variable:15s}"
                f"  F = {F:.3f}"
                f"  p = {p:.4f}"
                f"  cutoff = {cutoff:.4f}"
            )

    # Fit and return the final model.

    return fit_model(selected)


# ------------------------------------------------
# 4C. Forward selection at alpha = 0.05
# ------------------------------------------------

# Start with the intercept-only model.
#
# A predictor enters the model if its partial F-test
# p-value is less than 0.05.

reg_forward = select_F(
    direction="forward",
    alpha=0.05
)

print("\nFORWARD SELECTION: alpha = 0.05")

print("Selected predictors:")
print(reg_forward.model.exog_names)

print("\nRegression coefficients:")
print(reg_forward.params)


# ------------------------------------------------
# 4D. Forward selection at alpha = 0.20
# ------------------------------------------------

# Increasing alpha makes it easier for a predictor
# to enter the model.
#
# Consequently, larger models may be selected.

reg_forward20 = select_F(
    direction="forward",
    alpha=0.20
)

print("\nFORWARD SELECTION: alpha = 0.20")

print("Selected predictors:")
print(reg_forward20.model.exog_names)

print("\nRegression coefficients:")
print(reg_forward20.params)


# ------------------------------------------------
# 4E. Forward selection at alpha = 0.001
# ------------------------------------------------

# Decreasing alpha makes the criterion for entering
# the model much more stringent.
#
# The selected model may contain very few predictors
# or even only an intercept.

reg_forward001 = select_F(
    direction="forward",
    alpha=0.001
)

print("\nFORWARD SELECTION: alpha = 0.001")

print("Selected predictors:")
print(reg_forward001.model.exog_names)

print("\nRegression coefficients:")
print(reg_forward001.params)


# ------------------------------------------------
# 4F. Backward elimination
# ------------------------------------------------

# Backward elimination starts with the full model.
#
# At each step, remove the predictor with the largest
# partial F-test p-value if it exceeds alpha = 0.05.

reg_backward = select_F(
    direction="backward",
    alpha=0.05
)

print("\nBACKWARD ELIMINATION: alpha = 0.05")

print("Selected predictors:")
print(reg_backward.model.exog_names)

print("\nRegression coefficients:")
print(reg_backward.params)


# ------------------------------------------------
# 4G. Trace the backward elimination procedure
# ------------------------------------------------

# The trace option displays each removed predictor,
# its partial F-statistic, and its p-value.
#
# This allows us to see how the regression model
# changes during variable selection.

reg_trace = select_F(
    direction="backward",
    alpha=0.05,
    trace=True
)

print("\nFINAL MODEL AFTER BACKWARD ELIMINATION")

print(reg_trace.summary())


# ------------------------------------------------
# 4H. Bonferroni correction
# ------------------------------------------------

# Sequential variable selection involves multiple
# hypothesis tests.
#
# When many tests are performed, the probability of
# at least one false rejection may increase.
#
# The Bonferroni correction reduces the significance
# level used for each individual test.
#
# At each selection step, we use:
#
#     adjusted alpha = alpha / m
#
# where m is the number of candidate tests at that step.
#
# This makes it harder for predictors to enter a model.
#
# IMPORTANT:
# This is a stepwise Bonferroni adjustment, not a
# guarantee of familywise error control over the
# entire adaptive model-selection procedure.


# Forward selection without Bonferroni correction.

reg_no_bonf = select_F(
    direction="forward",
    alpha=0.20
)

print("\nFORWARD SELECTION WITHOUT BONFERRONI")

print(reg_no_bonf.model.exog_names)


# Forward selection with Bonferroni correction.

reg_bonf = select_F(
    direction="forward",
    alpha=0.20,
    correction=True
)

print("\nFORWARD SELECTION WITH BONFERRONI")

print(reg_bonf.model.exog_names)


# ------------------------------------------------
# 4I. Backward elimination with Bonferroni correction
# ------------------------------------------------

# We can also apply the adjustment to backward
# elimination.
#
# Notice that the consequences may differ from
# forward selection: a smaller significance cutoff
# makes it easier to classify an included predictor
# as insufficiently significant and remove it.

reg_backward_bonf = select_F(
    direction="backward",
    alpha=0.05,
    correction=True
)

print("\nBACKWARD ELIMINATION WITH BONFERRONI")

print(reg_backward_bonf.model.exog_names)
FORWARD SELECTION: alpha = 0.05
Selected predictors:
['const', 'Population', 'GNP', 'Year']

Regression coefficients:
const        -184001.434804
Population        39.236469
GNP               -6.599244
Year              93.257600
dtype: float64

FORWARD SELECTION: alpha = 0.20
Selected predictors:
['const', 'Population', 'GNP', 'Year', 'Armed.Forces', 'Employed']

Regression coefficients:
const          -179186.345596
Population           4.431120
GNP                 -2.778379
Year                93.411989
Armed.Forces        -0.448541
Employed           -36.656337
dtype: float64

FORWARD SELECTION: alpha = 0.001
Selected predictors:
['const']

Regression coefficients:
const    319.33125
dtype: float64

BACKWARD ELIMINATION: alpha = 0.05
Selected predictors:
['const', 'GNP', 'Armed.Forces', 'Year', 'Employed']

Regression coefficients:
const          -182531.665656
GNP                 -2.457005
Armed.Forces        -0.483780
Year                95.425982
Employed           -39.505813
dtype: float64
Step 1: Removed GNP.deflator     F = 1.455  p = 0.2585  cutoff = 0.0500
Step 2: Removed Population       F = 0.412  p = 0.5354  cutoff = 0.0500

FINAL MODEL AFTER BACKWARD ELIMINATION
                            OLS Regression Results                            
==============================================================================
Dep. Variable:             Unemployed   R-squared:                       0.988
Model:                            OLS   Adj. R-squared:                  0.983
Method:                 Least Squares   F-statistic:                     219.0
Date:                Wed, 28 Oct 2026   Prob (F-statistic):           2.10e-10
Time:                        16:21:55   Log-Likelihood:                -59.665
No. Observations:                  16   AIC:                             129.3
Df Residuals:                      11   BIC:                             133.2
Df Model:                           4                                         
Covariance Type:            nonrobust                                         
================================================================================
                   coef    std err          t      P>|t|      [0.025      0.975]
--------------------------------------------------------------------------------
const        -1.825e+05   1.54e+04    -11.883      0.000   -2.16e+05   -1.49e+05
GNP             -2.4570      0.492     -4.992      0.000      -3.540      -1.374
Armed.Forces    -0.4838      0.053     -9.120      0.000      -0.601      -0.367
Year            95.4260      7.870     12.125      0.000      78.104     112.748
Employed       -39.5058      5.485     -7.202      0.000     -51.579     -27.433
==============================================================================
Omnibus:                        1.513   Durbin-Watson:                   3.006
Prob(Omnibus):                  0.469   Jarque-Bera (JB):                0.926
Skew:                           0.577   Prob(JB):                        0.629
Kurtosis:                       2.762   Cond. No.                     1.02e+07
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.02e+07. This might indicate that there are
strong multicollinearity or other numerical problems.

FORWARD SELECTION WITHOUT BONFERRONI
['const', 'Population', 'GNP', 'Year', 'Armed.Forces', 'Employed']

FORWARD SELECTION WITH BONFERRONI
['const', 'Population', 'GNP', 'Year', 'Armed.Forces', 'Employed']

BACKWARD ELIMINATION WITH BONFERRONI
['const', 'GNP', 'Armed.Forces', 'Year', 'Employed']
In [4]:
# ================================================================
# PART 5. VISUALIZATION: SCATTERPLOT MATRIX
# ================================================================

# A scatterplot matrix displays scatterplots for
# every pair of variables in the dataset.
#
# It is useful for examining:
#
#   1. Relationships between the response and predictors.
#   2. Whether these relationships appear linear.
#   3. Possible multicollinearity among predictors.
#
# The Longley dataset is well known for strong
# multicollinearity among its economic variables.
#
# This makes it a useful example for studying
# regression model selection.


# ------------------------------------------------
# 5A. Create the scatterplot matrix
# ------------------------------------------------

# pandas provides scatter_matrix(), which is similar
# to the plot(longley) command in R.

axes = scatter_matrix(
    longley,
    figsize=(12, 12),
    diagonal="hist",
    alpha=0.8
)

plt.suptitle(
    "Longley Data: Scatterplot Matrix",
    fontsize=15
)

plt.tight_layout()
plt.show()


# ------------------------------------------------
# 5B. Examine correlations
# ------------------------------------------------

# A correlation matrix provides a numerical summary
# of the linear relationships visible in the plots.
#
# Correlations close to +1 or -1 indicate strong
# linear relationships between pairs of variables.
#
# However, multicollinearity can also involve
# combinations of more than two predictors.

print("\nCORRELATION MATRIX")

print(longley.corr().round(3))
No description has been provided for this image
CORRELATION MATRIX
              GNP.deflator    GNP  Unemployed  Armed.Forces  Population  \
GNP.deflator         1.000  0.992       0.621         0.465       0.979   
GNP                  0.992  1.000       0.604         0.446       0.991   
Unemployed           0.621  0.604       1.000        -0.177       0.687   
Armed.Forces         0.465  0.446      -0.177         1.000       0.364   
Population           0.979  0.991       0.687         0.364       1.000   
Year                 0.991  0.995       0.668         0.417       0.994   
Employed             0.971  0.984       0.502         0.457       0.960   

               Year  Employed  
GNP.deflator  0.991     0.971  
GNP           0.995     0.984  
Unemployed    0.668     0.502  
Armed.Forces  0.417     0.457  
Population    0.994     0.960  
Year          1.000     0.971  
Employed      0.971     1.000  
In [ ]:
# ================================================================
# PART 6. EXPORT THE NOTEBOOK TO HTML
# ================================================================

# The following code creates an HTML version of the
# current Google Colab notebook.
#
# The HTML file contains the Python code, explanatory
# text, tables, and saved graphical output.
#
# It can be opened in a web browser without Colab.
#
# This is useful for distributing the completed lab
# through Canvas.
#
# Run this section AFTER executing the other cells,
# so their output is included in the exported notebook.


from google.colab import _message, files
from nbconvert import HTMLExporter
import nbformat
import json


# Retrieve the current Colab notebook.

notebook = _message.blocking_request(
    "get_ipynb",
    timeout_sec=60
)["ipynb"]


# Convert the notebook to the standard Jupyter format.

nb = nbformat.reads(
    notebook if isinstance(notebook, str)
    else json.dumps(notebook),
    as_version=4
)


# Convert the notebook to HTML.

html, resources = HTMLExporter().from_notebook_node(nb)


# Specify the name of the HTML file.

filename = "Py Lab 10 - Regression model selection continued.html"


# Save the HTML document.

with open(filename, "w", encoding="utf-8") as f:
    f.write(html)


# Download the HTML file to your computer.

files.download(filename)


# ================================================================
# END OF LAB 10
# ================================================================
In [ ]: